package com.itheima.boottlias.controller;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.itheima.boottlias.domain.pojo.Student;
import com.itheima.boottlias.domain.query.QueryParam;
import com.itheima.boottlias.domain.vo.PageResult;
import com.itheima.boottlias.domain.vo.Result;
import com.itheima.boottlias.service.StudentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;

/**
 * @author ghy
 * @version 1.0
 * @since 2025-07-11 14:56
 */
@RestController
@RequestMapping("/students")
@Slf4j
public class StudentController {

    @Autowired
    private StudentService studentService;

    @GetMapping
    public Result pageQuery(QueryParam queryParam){
        log.info("queryParam:{}", queryParam);
        PageResult<Student> pageResult = studentService.pageQuery(queryParam);
        return Result.success(pageResult);
    }

    @PostMapping
    public Result add(@RequestBody Student student) throws Exception {
        log.info("{}", student);
        //调用业务
        studentService.add(student);
        return Result.success();
    }

    @DeleteMapping("/{ids}")
    public Result deleteByIds(@PathVariable(name = "ids") String ids) throws Exception {
        if (StrUtil.isNotBlank(ids)) {
            String[] idStrs = ids.split(",");
            if(ArrayUtil.isNotEmpty(idStrs) && idStrs.length > 0) {
                // 使用Stream流将字符串数组转成整形数组
                Integer[] idList = Arrays.stream(idStrs).map(Integer::parseInt).toArray(Integer[]::new);
                studentService.deleteByIds(idList);
            }
        }
        return Result.success();
    }


    @GetMapping("/{id}")
    public Result findById(@PathVariable(name = "id") Integer id){
        Student student = studentService.findById(id);
        return Result.success(student);
    }

    @PutMapping
    public Result update(@RequestBody Student student){
        studentService.update(student);
        return Result.success();
    }

    @PutMapping("/violation/{id}/{score}")
    public Result violation(@PathVariable(name = "id") Integer id, @PathVariable(name = "score") Short score){
        studentService.violation(id, score);
        return Result.success();
    }


}
